---
import type {CollectionEntry} from "astro:content";
import removeMarkdown from "../utils/vendors/markdown-to-text";

interface Props {
  data: CollectionEntry<"blog">[];
}

const {data} = Astro.props;
const searchData = data?.map((post) => ({
  id: post.id,
  title: post.data.title,
  // 使用工具去除 Markdown 格式
  content: removeMarkdown(post.body),
  url: `/post/${post.slug}`,
  // tags: post.data.tags.join(","),
  // date: post.data.date
}));
---

<div id='koi-search-box-host' style='display: none;'>
  <div class='relative z-40'>
    <div>
      <div class='' style='display: contents;'>
        <button
          class='fixed size-full left-0 top-0 bg-black/40 backdrop-blur-xl'
        ></button>
      </div>
      <div class='fixed inset-0 overflow-y-auto'>
        <div class='flex max-h-full justify-center px-4 py-12 text-center'>
          <div style='display: contents;'>
            <div
              class='w-full max-w-2xl transform flex flex-col items-start rounded-xl bg-white dark:bg-primary-950 text-black dark:text-white text-left align-middle shadow-xl transition-all'
              id='headlessui-dialog:1'
              role='dialog'
              tabindex='-1'
              aria-modal='true'
              aria-label='博客全文搜索'
            >
              <div class='relative flex-none w-full'>
                <div
                  aria-hidden='true'
                  class='size-16 flex items-center justify-center absolute left-0 top-0 pointer-events-none'
                >
                  <svg
                    xmlns='http://www.w3.org/2000/svg'
                    width='1em'
                    height='1em'
                    viewBox='0 0 1664 1664'
                    class='size-5'
                    ><path
                      fill='currentColor'
                      d='M1152 704q0-185-131.5-316.5T704 256T387.5 387.5T256 704t131.5 316.5T704 1152t316.5-131.5T1152 704m512 832q0 52-38 90t-90 38q-54 0-90-38l-343-342q-179 124-399 124q-143 0-273.5-55.5t-225-150t-150-225T0 704t55.5-273.5t150-225t225-150T704 0t273.5 55.5t225 150t150 225T1408 704q0 220-124 399l343 343q37 37 37 90'
                    ></path></svg
                  >
                </div>
                <label for='koi-search-keyword-input' class='sr-only'
                  >搜索关键词：</label
                >
                <input
                  id='koi-search-keyword-input'
                  autocomplete='off'
                  class='block w-full h-16 ps-16 bg-transparent text-black dark:text-white focus:outline-0 focus:bg-gray-950/5 dark:focus:bg-gray-50/5 transition-colors placeholder-opacity-30 border-b border-gray-950/5 dark:border-gray-50/5 focus:border-transparent dark:focus:border-transparent rounded-t-xl rounded-b-none'
                  placeholder='输入搜索关键词……'
                  data-posts={JSON.stringify(searchData)}
                />
              </div>
              <ul
                id='koi-search-keyword-result'
                class='p-4 space-y-4 flex-auto w-full max-h-full overflow-y-auto'
              >
              <div class='py-16 w-full flex items-center justify-center opacity-60'>来搜索点什么吧w</div>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script lang='js'>
  // 将构建时生成的数据注入到前端
  //  window.__SEARCH_DATA__ = {posts: ${JSON.stringify(searchData)}};
  // 如果你想要在页面加载后添加事件监听器
  const searchInputEl = document.getElementById("koi-search-keyword-input");
  const keywordSearchResultEl = document.getElementById(
    "koi-search-keyword-result"
  );
  const posts = JSON.parse(searchInputEl.dataset.posts);

  searchInputEl?.addEventListener("input", (e) => {
    performSearch(e.target.value);
  });
  // 防抖函数优化性能
  let timeoutId;
  function debounce(fn, delay = 300) {
    return (...args) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => fn(...args), delay);
    };
  }

  // 核心搜索逻辑
  function performSearch(keyword) {
    const normalizedKeyword = keyword.trim().toLowerCase();
    if (!normalizedKeyword) {
      keywordSearchResultEl.innerHTML = `<div class='py-16 w-full flex items-center justify-center opacity-60'>来搜索点什么吧w</div>`;
      return;
    }

    const results = posts.filter((post) => {
      const searchContent =
        `${post.title} ${post.content} ${post.tags}`.toLowerCase();
      return searchContent.includes(normalizedKeyword);
    });

    renderResults(results, normalizedKeyword);
  }

  // 结果渲染（带高亮）
  function renderResults(results, keyword) {
    if (results.length === 0) {
      keywordSearchResultEl.innerHTML =
        '<div class="py-4 text-center">没有找到相关结果</div>';
      return;
    }

    keywordSearchResultEl.innerHTML = results
      .map(
        (post) => `
                      <li>
      <a href="${post.url}" class="flex items-start bg-gray-950/5 dark:bg-gray-50/5 rounded-md hover:bg-primary-700 dark:hover:bg-primary-700 hover:text-white active:bg-primary-700 dark:active:bg-primary-700 active:text-white">
          <div class='flex-none size-14 flex items-center justify-center'>
                            <svg
                              class='size-6'
                              xmlns='http://www.w3.org/2000/svg'
                              width='1em'
                              height='1em'
                              viewBox='0 0 24 24'
                            >
                              <path
                                fill='currentColor'
                                d='M7 17h7v-2H7zm0-4h10v-2H7zm0-4h10V7H7zM5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h14q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21zm0-2h14V5H5zM5 5v14z'
                              />
                            </svg>
                          </div>
                          <div class='flex-auto min-w-0 space-y-2 py-4 pe-4'>
                            <h2 class='truncate'>${highlight(post.title, keyword)}</h2>
                            <p class='text-sm opacity-60'>
                              ${highlight(
                                post.content.length > 200
                                  ? post.content.slice(0, 200) + "..."
                                  : post.content
                              )}
                            </p>
                          </div>
      </a>
      </li>
    `
      )
      .join("");
  }

  // 关键词高亮函数
  function highlight(text, keyword) {
    const regex = new RegExp(`(${keyword})`, "gi");
    return text.replace(regex, '<span class=" bg-yellow-200 dark:bg-yellow-800 px-1 rounded;">$1</span>');
  }
</script>
